<template>
  <div ref="mPage" class="m-page" :style="{ backgroundColor: bgColor }">
    <div class="m-page-bg" :style="contStyles"></div>
    <div class="m-page-wrapper" :class="{ 'm-white-barcolor': whiteBarColor }">
      <slot name="head"></slot>
      <div class="page-container"><slot></slot></div>
      <slot name="foot"></slot>
    </div>
  </div>
</template>
<script>
import { defineComponent, computed, toRefs } from 'vue'

// hex -> rgb
// eslint-disable-next-line
function hexToRgb(hex) {
  return (
    'rgb(' +
    parseInt('0x' + hex.slice(1, 3)) +
    ',' +
    parseInt('0x' + hex.slice(3, 5)) +
    ',' +
    parseInt('0x' + hex.slice(5, 7)) +
    ')'
  )
}

// hex -> rgba
function hexToRgba(hex, opacity) {
  return (
    'rgba(' +
    parseInt('0x' + hex.slice(1, 3)) +
    ',' +
    parseInt('0x' + hex.slice(3, 5)) +
    ',' +
    parseInt('0x' + hex.slice(5, 7)) +
    ',' +
    opacity +
    ')'
  )
}

export default defineComponent({
  name: 'MPage',
  props: {
    bgImage: {
      type: String,
      default: '',
    },
    bgColor: {
      type: String,
      default: '#f5f5f5',
    },
    primary: {
      type: Array,
      default: () => [],
    },
    whiteBarColor: {
      type: Boolean,
    },
  },
  setup (props) {
    const { primary, bgImage, bgColor } = toRefs(props)

    const contStyles = computed(() => {
      const [color, deepColor] = primary.value
      const syl = {}
      if (bgImage.value) {
        syl.backgroundImage = `linear-gradient(to top, ${bgColor.value}, transparent),url("${bgImage.value}")`
        syl.backgroundSize = 'cover'
        syl.backgroundPosition = 'top center'
      } else if (color && deepColor)
        syl.backgroundImage = `linear-gradient(0deg, rgba(245,245,245,0.00) 0%, ${color} 38%, ${color} 79%, ${deepColor} 100%)`
      else if (color)
        syl.backgroundImage = `linear-gradient(0deg, rgba(245,245,245,0.00) 0%, ${hexToRgba(
          color,
          0.1
        )} 10%, ${hexToRgba(color, 0.3)} 20%, ${hexToRgba(
          color,
          0.8
        )} 50%, ${color} 100%)`
      return {
        ...syl,
      }
    })

    return {
      contStyles
    }
  }
})
</script>
<style lang="less" scoped>
.m-page {
  height: 100%;
  position: relative;
  z-index: 2;
  &-bg {
    height: 298px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
  &-wrapper {
    position: relative;
    z-index: 2;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-repeat: no-repeat;
    .page-container {
      flex: 1;
      overflow-x: hidden;
      overflow-y: auto;
      scrollbar-width: thin;
      -webkit-overflow-scrolling: touch;
    }
  }
  .m-white-barcolor {
    :deep(.m-nav-title),
    :deep(.m-nav-arrow) {
      color: #fff;
    }
  }
}
</style>
